import { defineComponent, ref, toRefs, reactive, onBeforeMount, watchEffect } from 'vue';
import draggable from 'vuedraggable';
import { IParam } from 'ibz-core';
import { AppDashboardDesignService } from '../../ui-service';

const AppDashboardDesignProps = {
  /**
   * @description 应用上下文
   * @type {*}
   * @memberof AppDashboardDesignProps
   */
  navContext: {
    type: Object,
  },
  /**
   * @description 视图参数
   * @type {*}
   * @memberof AppDashboardDesignProps
   */
  navParam: {
    type: Object,
  },
  /**
   * 模型服务
   * @type {Object}
   * @memberof InputBox
   */
  modelService: Object,
};

//  数据看板自定义组件
export const AppDashboardDesign = defineComponent({
  name: 'AppDashboardDesign',
  props: AppDashboardDesignProps,
  components: {
    draggable,
  },
  setup(props: any, ctx: any) {
    /**
     * @description 选中门户集合
     * @type {IParam[]}
     */
    const selections: IParam[] = reactive([]);

    /**
     * @description 未选中门户集合
     * @type {IParam[]}
     */
    const notSelections: IParam[] = reactive([]);

    /**
     * @description 显示状态
     * @type {boolean}
     */
    const titleStatus = ref(true);

    /**
     * @description 面板设计服务
     * @type {AppDashboardDesignService}
     */
    const designService: AppDashboardDesignService = AppDashboardDesignService.getInstance();

    /**
     * @description 部件挂载之前
     */
    onBeforeMount(() => {
      const { navContext, navParam } = toRefs(props);
      designService.loadPortletList(navContext.value, navParam.value).then((result: IParam) => {
        handleSelections(result.data);
      });
    });

    /**
     * @description 监听
     */
    watchEffect(() => {
      if (selections.length > 0) {
        selections.forEach((selection: IParam, index: number) => {
          selection.id = index + 1;
        });
      }
      if (notSelections.length > 0) {
        notSelections.forEach((notSelection: IParam, index: number) => {
          notSelection.id = index + 1;
        });
      }
    });

    /**
     * @description 处理选中数据
     */
    const handleSelections = (items: IParam[]) => {
      const { navParam } = toRefs(props);
      const customModel = navParam.value?.customModel || [];
      items.forEach((item: IParam) => {
        const custom = customModel.find((_custom: any) => {
          return _custom.codeName == item.portletCodeName;
        });
        if (custom) {
          selections.push(item);
        } else {
          notSelections.push(item);
        }
      });
    };

    /**
     * @description 保存模型数据
     */
    const saveModel = (isReset: boolean = false) => {
      const { navParam, navContext } = toRefs(props);
      const tempViewParam = {};
      Object.assign(tempViewParam, {
        ...navParam.value,
        model: isReset ? [] : selections,
      });
      designService.saveModelData(navParam.value?.utilServiceName, navContext.value, tempViewParam);
    };

    /**
     * @description 删除选中项
     */
    const deleteItem = (id: number) => {
      const index = selections.findIndex((item: IParam) => item.id === id);
      if (index !== -1) {
        notSelections.push(selections[index]);
        selections.splice(index, 1);
        saveModel();
      }
    };

    /**
     * @description 添加选中项
     */
    const addItem = (id: number) => {
      const index = notSelections.findIndex((item: IParam) => item.id === id);
      if (index !== -1) {
        selections.push(notSelections[index]);
        notSelections.splice(index, 1);
        saveModel();
      }
    };

    /**
     * @description 拖拽结束
     */
    const dragEnd = () => {
      saveModel();
    };

    /**
     * @description 视图关闭
     */
    const closeView = (event: any) => {
      ctx.emit('viewEvent', { viewName: 'app-dashboard-design', action: 'onClose', data: [] });
    };

    return {
      closeView,
      selections,
      dragEnd,
      deleteItem,
      notSelections,
      titleStatus,
      addItem,
    };
  },
  methods: {
    renderHeader() {
      return (
        <ion-header>
          <ion-toolbar class='view-header'>
            <ion-buttons slot='start'>
              <ion-button
                onClick={(event: any) => {
                  this.closeView(event);
                }}
              >
                <app-icon name='chevron-back' />
                {`${(this as any).$tl('common.dashboard.close', '关闭')}`}
              </ion-button>
            </ion-buttons>
            <ion-title>
              <label class='title-label'>
                {`${(this as any).$tl('common.dashboard.customdatakanban', '自定义数据看板')}`}
              </label>
            </ion-title>
          </ion-toolbar>
        </ion-header>
      );
    },
    renderContent() {
      return (
        <ion-content>
          <div class='dashboard-list'>
            <div class='dashboard-list-item list-item--added'>
              <div class='list-item-header'>
                {`${(this as any).$tl('common.dashboard.existcard', '已经添加的卡片')}`}
              </div>
              <draggable
                list={this.selections}
                handle='.list-item-content-end'
                itemKey='id'
                animation={200}
                onEnd={this.dragEnd}
                v-slots={{
                  item: ({ element, index }: any) => {
                    return (
                      <div class='list-item-content' key={element.componentName}>
                        <div class='list-item-content-start'>
                          <app-icon
                            onClick={() => {
                              this.deleteItem(element.id);
                            }}
                            name='remove-circle-outline'
                          />
                        </div>
                        <div class='list-item-pic'>
                          <img src={element.portletImage ? element.portletImage : 'assets/images/portlet.jpg'} alt='' />
                        </div>
                        <div class='list-item-text'>
                          <div>
                            <span>{element.portletName}</span>
                            <div>
                              {element.detailText
                                ? element.detailText
                                : `${(this as any).$tl('common.dashboard.nodescription', '暂无描述')}`}
                            </div>
                          </div>
                        </div>
                        <div class='list-item-content-end'>
                          <app-icon name='swap-vertical-outline'></app-icon>
                        </div>
                      </div>
                    );
                  },
                }}
              ></draggable>
            </div>

            <div class='dashboard-list-item dashboard-list-item--add'>
              <div class='list-item-header'>
                {`${(this as any).$tl('common.dashboard.noexistcard', '可添加的卡片')}`}
              </div>
              {this.notSelections.map((item: any, index: number) => {
                return (
                  <div class='list-item-content' key={index}>
                    <div class='list-item-content-start'>
                      <app-icon
                        onClick={() => {
                          this.addItem(item.id);
                        }}
                        name='add-circle-outline'
                      />
                    </div>
                    <div class='list-item-pic'>
                      <img src={item.portletImage ? item.portletImage : 'assets/images/portlet.jpg'} alt='' />
                    </div>
                    <div class='list-item-text'>
                      <div>
                        <span>{item.portletName}</span>
                        <div>
                          {item.detailText
                            ? item.detailText
                            : `${(this as any).$tl('common.dashboard.nodescription', '暂无描述')}`}
                        </div>
                      </div>
                    </div>
                    <div class='list-item-content-end'>{/* <app-icon name="swap-vertical-outline"></app-icon> */}</div>
                  </div>
                );
              })}
            </div>
          </div>
        </ion-content>
      );
    },
  },
  render() {
    return (
      <div class={'app-dashboard-design'}>
        {this.titleStatus ? this.renderHeader() : null}
        {this.renderContent()}
      </div>
    );
  },
});
